﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace UI
{
    public class RushEliteBossPage : Page 
    {
        public GameObject bossIconPrefab;
        public GameObject itemIconPrefab;

        public UIGrid bossIconGrid;
        public UIScrollView bossIconScrollView;

        public UILabel bossDescLabel;

        public UIGrid itemIconGrid;
        public UIScrollView itemIconScrollView;

        public UILabel leftChanllegeTimeLabel;

        public RushEliteBossBuyTimePanel buyTimePanel;

        public GameObject fightBtn;

        List<GameObject> bossIconCache = new List<GameObject>();
        List<GameObject> bossItemCache = new List<GameObject>();

        string currentSelectBossId = "";

        int leftChallengeTime;
        int diamondChallengeBuyTime;
        int diamondChallengeBuyCost;

        protected override void DoOpen()
        {
            onRushEliteBossTimeValueChange += StaticData.funcNavKit.OnRushEliteBossTimeCost;
            ProtoBuf.Message.CSGetRushEliteBossInfo msg = new ProtoBuf.Message.CSGetRushEliteBossInfo();
            NetAPI.SendHttp(ProtoBuf.Message.OpDefine.CSGetRushEliteBossInfo, msg, (pack, b) => {
                if (b)
                {
                    ProtoBuf.Message.SCGetRushEliteBossInfo _msg = pack.kBody as ProtoBuf.Message.SCGetRushEliteBossInfo;
                    Refresh(_msg);
                }
            });
        }

        public override void DoReopen()
        {
            ProtoBuf.Message.CSGetRushEliteBossInfo msg = new ProtoBuf.Message.CSGetRushEliteBossInfo();
            NetAPI.SendHttp(ProtoBuf.Message.OpDefine.CSGetRushEliteBossInfo, msg, (pack, b) => {
                if (b)
                {
                    ProtoBuf.Message.SCGetRushEliteBossInfo _msg = pack.kBody as ProtoBuf.Message.SCGetRushEliteBossInfo;
                    Refresh(_msg);
                }

            });
        }

        public override void OnCoverPageRemove()
        {
            ProtoBuf.Message.CSGetRushEliteBossInfo msg = new ProtoBuf.Message.CSGetRushEliteBossInfo();
            NetAPI.SendHttp(ProtoBuf.Message.OpDefine.CSGetRushEliteBossInfo, msg, (pack, b) => {
                if (b)
                {
                    ProtoBuf.Message.SCGetRushEliteBossInfo _msg = pack.kBody as ProtoBuf.Message.SCGetRushEliteBossInfo;
                    Refresh(_msg);
                }

            });
        }

        protected override void DoClose()
        {
            remoteData = null;
            currentSelectBossId = "";
            onRushEliteBossTimeValueChange -= StaticData.funcNavKit.OnRushEliteBossTimeCost;
        }

        ProtoBuf.Message.SCGetRushEliteBossInfo remoteData = null;


        public ProtoBuf.Message.RushEliteBossInfo GetPreRushEliteBossInfo(string bossId)
        {
            if (remoteData != null)
            {
                int index = 0;
                for (int i = 0; i < remoteData.bossInfoList.Count; ++i)
                {
                    if (remoteData.bossInfoList[i].eliteTaskId == bossId)
                    {
                        index = i - 1;
                        break;
                    }
                }

                if (index >= 0 && index < remoteData.bossInfoList.Count)
                {
                    return remoteData.bossInfoList[index];

                }
            }
            return null;

        }
        
        ProtoBuf.Message.RushEliteBossInfo GetRushEliteBossInfo(string bossId)
        {
            if (remoteData != null)
            {
                foreach (var info in remoteData.bossInfoList)
                {
                    if (info.eliteTaskId == bossId)
                    {
                        return info;
                    }
                }
            }
            return null;
        }

        void Refresh(ProtoBuf.Message.SCGetRushEliteBossInfo msg)
        {
            StaticData.ReceiveRushEliteBossInfo(msg);
            remoteData = msg;
            GameObject selectObj = null;
            GameObject lastObj = null;

            foreach (var obj in bossIconCache)
            {
                GameObject.Destroy(obj);
            }
            bossIconCache.Clear();

            foreach (var info in msg.bossInfoList)
            {
                var obj = GameObject.Instantiate(bossIconPrefab) as GameObject;
                obj.GetComponent<RushEliteBossIcon>().Init(info, false, OnBossIconClick, this);
                obj.transform.SetParent(bossIconGrid.transform);
                obj.transform.localPosition = Vector3.zero;
                obj.transform.localScale = Vector3.one;
                obj.transform.localEulerAngles = Vector3.zero;
                bossIconCache.Add(obj);
                if (!string.IsNullOrEmpty(currentSelectBossId))
                {
                    if (info.eliteTaskId == currentSelectBossId)
                    {
                        selectObj = obj;
                    }
                }
                if (info.isOpen > 0)
                {
                    lastObj = obj;
                }
            }
            bossIconGrid.repositionNow = true;

            if (selectObj == null)
            {
                selectObj = lastObj;
            }
            if (selectObj != null)
            {
                OnBossIconClick(selectObj);
            }
            else
            {
                bossDescLabel.text = "";
                fightBtn.SetActive(false);
            }

            leftChallengeTime = msg.leftTime;
            if (onRushEliteBossTimeValueChange != null)
            {
                onRushEliteBossTimeValueChange(leftChallengeTime);
            }
            leftChanllegeTimeLabel.text = string.Format("{0}/{1}", msg.leftTime, msg.totalTime);
            diamondChallengeBuyTime = msg.diamondLeftTime;
            diamondChallengeBuyCost = msg.diamondLeftTimeCost;
        }

        void RefreshBossDetail(string bossId)
        {
            var db = Dict.Blo.DictRushBlo.GetTableRushEliteBoss(bossId);
            if (db != null)
            {
                bossDescLabel.text = TableTextBlo.GetText(db.EliteBossDesc);
            }
            foreach (var obj in bossItemCache)
            {
                GameObject.Destroy(obj);
            }
            bossItemCache.Clear();

            var data = GetRushEliteBossInfo(bossId);
            foreach (var reward in data.firstRewardList)
            {
                var obj = GameObject.Instantiate(itemIconPrefab) as GameObject;
                obj.GetComponent<RushEliteBossItem>().Init(reward, true);
                obj.transform.SetParent(itemIconGrid.transform);
                obj.transform.localPosition = Vector3.zero;
                obj.transform.localScale = Vector3.one;
                obj.transform.localEulerAngles = Vector3.zero;
                bossItemCache.Add(obj);
            }
            foreach (var reward in data.generalRewardList)
            {
                var obj = GameObject.Instantiate(itemIconPrefab) as GameObject;
                obj.GetComponent<RushEliteBossItem>().Init(reward, false);
                obj.transform.SetParent(itemIconGrid.transform);
                obj.transform.localPosition = Vector3.zero;
                obj.transform.localScale = Vector3.one;
                obj.transform.localEulerAngles = Vector3.zero;
                bossItemCache.Add(obj);
            }

            itemIconGrid.repositionNow = true;
        }


        void OnBossIconClick(GameObject obj)
        {
            foreach (var icon in bossIconCache)
            {
                if (icon == obj)
                {
                    icon.GetComponent<RushEliteBossIcon>().Select();
                }
                else
                {
                    icon.GetComponent<RushEliteBossIcon>().UnSelect();
                }
            }
            currentSelectBossId = obj.GetComponent<RushEliteBossIcon>().GetBossId();
            RefreshBossDetail(currentSelectBossId);
            if (!obj.GetComponent<RushEliteBossIcon>().IsOpen())
            {
                fightBtn.SetActive(false);
            }
            else
            {
                fightBtn.SetActive(true);
            }
        }


        public void OnFightBtnClick()
        {
            if (leftChallengeTime <= 0)
            {
                BoxManager.CreatePopupTextBox(TableTextBlo.GetText("left_times_not_enough"));
                return;
            }
            ProtoBuf.Message.CSRushFightStart msg = new ProtoBuf.Message.CSRushFightStart();
            msg.rushType = 2;
            msg.taskId = currentSelectBossId;
            NetAPI.SendHttp(ProtoBuf.Message.OpDefine.CSRushFightStart, msg, (pack, b) => {
                if (b)
                {
                    ProtoBuf.Message.SCRushFightStart _msg = pack.kBody as ProtoBuf.Message.SCRushFightStart;
                    StaticData.curBattleData.SetData(_msg, false);
                    StartCoroutine(ToBattle());
                }
            });
        }

        IEnumerator ToBattle()
        {
            LoadingPanel.Instance.ShowMask(0.5f);
            yield return new WaitForSeconds(0.5f);
            ManagerController.Instance.RushToBattle();
        }

        public void OnBuyChanllegeTimeBtnClick()
        {
            if (diamondChallengeBuyTime <= 0)
            {
                BoxManager.CreatePopupTextBox(TableTextBlo.GetText("today_buy_times_off"));
                return;
            }
            buyTimePanel.Enter(diamondChallengeBuyTime, diamondChallengeBuyCost);
        }

        #region OnRushEliteBossTimeValueChange
        public delegate void OnRushEliteBossTimeValueChange(int curValue);
        OnRushEliteBossTimeValueChange onRushEliteBossTimeValueChange;
        #endregion
    }
}
